/*
 * screensaverdeactivator.cpp - Deactivate screensaver
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "screensaverdeactivator.h"

ScreenSaverDeactivator::ScreenSaverDeactivator(QObject *parent) :
    QObject(parent)
{
    checksaverProcess = new QProcess(this);
    blockXscreensaverProcess = new QProcess(this);
    blockGnomescreensaverProcess = new QProcess(this);
    xtimer = new QTimer(this);

    connect(xtimer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
}

QHash<QString, bool> ScreenSaverDeactivator::screenSaverCheck()
{
    QHash<QString, bool> screensavers;
    QByteArray result;

    if (checksaverProcess->state())
            checksaverProcess->kill();
    checksaverProcess->start("xscreensaver-command", QStringList() << "-version");
    checksaverProcess->waitForFinished(1000);
    result = checksaverProcess->readAllStandardOutput();
    checksaverProcess->close();
    screensavers.insert("xscreensaver", (result.indexOf("XScreenSaver") != -1));

    if (checksaverProcess->state())
            checksaverProcess->kill();
    checksaverProcess->start("gnome-screensaver-command", QStringList() << "--query");
    checksaverProcess->waitForFinished(1000);
    result = checksaverProcess->readAllStandardError();
    checksaverProcess->close();
    screensavers.insert("gnome-screensaver", checksaverProcess->error() == 5 &&
                        !(result.indexOf("Screensaver is not running") != -1));

    return screensavers;
}

void ScreenSaverDeactivator::xDeactivate()
{
    xtimer->start(500);
}

void ScreenSaverDeactivator::xActivate()
{
    xtimer->stop();
}

void ScreenSaverDeactivator::gActivate()
{
    blockGnomescreensaverProcess->close();
}

void ScreenSaverDeactivator::gDeactivate()
{
    if (blockGnomescreensaverProcess->state())
        blockGnomescreensaverProcess->kill();
    blockGnomescreensaverProcess->start("gnome-screensaver-command", QStringList() << "-i");
}

void ScreenSaverDeactivator::timerUpdate()
{
    if (blockXscreensaverProcess->state())
        blockXscreensaverProcess->kill();
    blockXscreensaverProcess->start("xscreensaver-command", QStringList() << "-deactivate");
}
